import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
const service = axios.create({ // 创建一个新的axios实例
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})
service.interceptors.request.use((config) => {
  // 注入token
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, (error) => {
  return Promise.reject(error) // 终止当前promise执行
})
// 响应拦截器
service.interceptors.response.use((response) => {
  const { data, message, success } = response.data
  if (success) {
    return data
  } else {
    Message({
      type: 'error',
      message: message
    })
    return Promise.reject(new Error(message))
  }
}, (error) => {
  // 错误提示
  Message({
    type: 'error',
    message: error.message
  })
})
export default service
